package com.cmccgz.udacs_landlord_webapp.main.host;

import android.Manifest;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.support.annotation.NonNull;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.util.Log;
import android.util.TypedValue;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.cmccgz.baselibrary.base.BaseActivity;
import com.cmccgz.baselibrary.base.PermissionUtils;
import com.cmccgz.baselibrary.image.GlideUtils;
import com.cmccgz.baselibrary.interfaces.OnObservableScrollListener;
import com.cmccgz.baselibrary.utils.ScreenUtils;
import com.cmccgz.baselibrary.utils.StringUtils;
import com.cmccgz.baselibrary.utils.ToastUtils;
import com.cmccgz.baselibrary.view.ObservableScrollView;
import com.cmccgz.udacs_landlord_webapp.R;
import com.cmccgz.udacs_landlord_webapp.base.AppConfig;
import com.cmccgz.udacs_landlord_webapp.bean.DeviceInfoBean;
import com.cmccgz.udacs_landlord_webapp.bean.HostMenuBean;
import com.cmccgz.udacs_landlord_webapp.bean.PushRequestBean;
import com.cmccgz.udacs_landlord_webapp.bean.UserInfo;
import com.cmccgz.udacs_landlord_webapp.bean.WebBean;
import com.cmccgz.udacs_landlord_webapp.jpush.AccreditListActivity;
import com.cmccgz.udacs_landlord_webapp.main.user.userinfo.UserInfoActivity;
import com.cmccgz.udacs_landlord_webapp.main.user.userinfo.UserInfoContract;
import com.cmccgz.udacs_landlord_webapp.main.user.userinfo.UserInfoPresenter;
import com.cmccgz.udacs_landlord_webapp.main.warning.WarningActivity;
import com.cmccgz.udacs_landlord_webapp.update.CheckUpdate;
import com.cmccgz.udacs_landlord_webapp.utils.BluetoothOpenDoorUtil;
import com.cmccgz.udacs_landlord_webapp.utils.ViewHelper;

import java.io.Serializable;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.cmccgz.udacs_landlord_webapp.main.host.HostActivity.CLOSE_HOST;
import static com.cmccgz.udacs_landlord_webapp.utils.BluetoothOpenDoorUtil.REQUEST_ENABLE_BT;

/**
 * @author INX
 *         租客端首页
 */
public class CHostActivity extends BaseActivity implements View.OnClickListener, HostContract.View, UserInfoContract.UserInfoView {
    private HostContract.Presenter presenter;
    private ImageView ci_header;
    private Button btn_blue_t, btn_net, btn_service, btn_warning;
    public final static String KEY_USERINFO = "key_userinfo";
    private UserInfoPresenter userInfoPresenter;
    private TextView tv_userName;
    private static final int LOCATION_PERMISSION_ASK = 0x77;
    private boolean isBluetoothEnable;
    public static final String UPDATE_USERINFO = "update_userinfo";
    private BroadcastReceiver mReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            switch (intent.getAction()) {
                case CLOSE_HOST:
                    finish(false);
                    break;
                case UPDATE_USERINFO:
                    userInfoPresenter.getUserInfo();
                    break;
            }
        }
    };
    private LinearLayout ll_op;
    private ViewHelper mViewHelper;
    private List<PushRequestBean> pushRequestDatas = new ArrayList<>();
    private static final int REQ_ACCREDITE_LIST = 101;

    private PermissionUtils.PermissionAskCallback permissionCallback = new PermissionUtils.PermissionAskCallback() {
        @Override
        public void hasPermissionDoNext() {
            checkBlueTooth();
        }
    };


    @Override
    protected int setLayoutId() {
        return R.layout.activity_c_host;
    }

    @Override
    protected void initView() {

        userInfoPresenter = new UserInfoPresenter(this);
        ci_header = ((ImageView) findViewById(R.id.ci_header));
        btn_blue_t = ((Button) findViewById(R.id.btn_blue_t));
        btn_net = ((Button) findViewById(R.id.btn_net));
        tv_userName = ((TextView) findViewById(R.id.tv_userName));
        btn_service = (Button) findViewById(R.id.btn_service);
        btn_warning = (Button) findViewById(R.id.btn_warning);
        ll_op = ((LinearLayout) findViewById(R.id.ll_op));
        ci_header.setOnClickListener(this);
        btn_blue_t.setOnClickListener(this);
        btn_net.setOnClickListener(this);
        btn_service.setOnClickListener(this);
        btn_warning.setOnClickListener(this);
        mViewHelper = ViewHelper.instance(this);
        if (mViewHelper != null) {
            mViewHelper.setTitle("首页");
            mViewHelper.setAllVisable(false);
            mViewHelper.setImageRightVisable(true);
            mViewHelper.setImageLeftVisable(true);
            mViewHelper.setImageRight(R.drawable.ic_msg);
        }
        initPageView();
        new HostPresenter(this);
        initDatas();
        IntentFilter filter = new IntentFilter();
        filter.addAction(CLOSE_HOST);
        filter.addAction(UPDATE_USERINFO);
        registerReceiver(mReceiver, filter);
        syncDevice();
        initBluetooth();
        presenter.getReqList("", "", "1");

        checkUpdate();
    }

    public void checkUpdate() {
        // 检查更新
        CheckUpdate.getInstance().start(this, false);
    }

    private void initBluetooth() {
        int state = BluetoothOpenDoorUtil.checkBlueEnable(this);
        switch (state) {
            case BluetoothOpenDoorUtil.STATE_BLUETOOTH_LE_FEATURE_UNABLE:
            case BluetoothOpenDoorUtil.STATE_BLUETOOTH_UNABLE:
                isBluetoothEnable = false;
                break;
            case BluetoothOpenDoorUtil.STATE_BLUETOOTH_ENABLE:
                isBluetoothEnable = true;
                break;
            default:
                isBluetoothEnable = false;
                break;
        }
    }

    private void syncDevice() {
        Intent intent = new Intent(mContext, SyncDeviceIntentService.class);
        mContext.startService(intent);
    }

    private void initPageView() {
        ViewGroup.LayoutParams layoutParams = ll_op.getLayoutParams();
        int titleHeight = getActionBarHeight();
        int statusBarHeight = getStatusBarHeight();
        layoutParams.height = ScreenUtils.getScreenHeight(mContext) - titleHeight - statusBarHeight;
        ll_op.setLayoutParams(layoutParams);
        ObservableScrollView sv = (ObservableScrollView) findViewById(R.id.sv);
        final View ly_title = findViewById(R.id.ly_title);
        //头像
        ViewGroup.LayoutParams lp_iv = mViewHelper.getIv_left().getLayoutParams();
        lp_iv.height = titleHeight - ScreenUtils.dpToPxInt(mContext, 12);
        lp_iv.width = titleHeight - ScreenUtils.dpToPxInt(mContext, 12);
        mViewHelper.getIv_left().setLayoutParams(lp_iv);
        mViewHelper.getIv_left().setAlpha(0f);
        mViewHelper.getIv_left().setClickable(false);
        sv.setScrollViewListener(new OnObservableScrollListener() {
            @Override
            public void onScrollChanged(ObservableScrollView scrollView, int x, int y, int oldx, int oldy) {
                int[] outLocation = new int[2];
                ll_op.getLocationOnScreen(outLocation);
                float alpha = 1 - (outLocation[1] - ly_title.getBottom()) / 100.0f;
                alpha = alpha < 0 ? 0 : alpha > 1 ? 1 : alpha;
                mViewHelper.getIv_left().setClickable(alpha > 0);
                mViewHelper.getIv_left().setAlpha(alpha);
                Log.e("INX", "run: ll_op-getTop=" + outLocation[1] + ",ly_title-getBottom=" + ly_title.getBottom() + ", mViewHelper.getIv_left()=" + mViewHelper.getIv_left().getAlpha());
            }
        });

    }

    /**
     * 获取actionbar的像素高度，默认使用android官方兼容包做actionbar兼容
     *
     * @return
     */
    private int getActionBarHeight() {

        int actionBarHeight = 0;
        if (getSupportActionBar() != null && (actionBarHeight = getSupportActionBar().getHeight()) == 0) {
            return actionBarHeight;
        }

        final TypedValue tv = new TypedValue();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
            if (getTheme().resolveAttribute(android.R.attr.actionBarSize, tv, true)) {
                actionBarHeight = TypedValue.complexToDimensionPixelSize(
                        tv.data, getResources().getDisplayMetrics());
            }
        } else {
            // 使用android.support.v7.appcompat包做actionbar兼容的情况
            if (getTheme().resolveAttribute(android.support.v7.appcompat.R.attr.actionBarSize, tv, true)) {
                actionBarHeight = TypedValue.complexToDimensionPixelSize(
                        tv.data, getResources().getDisplayMetrics());
            }

        }

        return actionBarHeight;
    }

    private int getStatusBarHeight() {
        Class<?> c = null;

        Object obj = null;

        Field field = null;

        int x = 0, sbar = 0;

        try {

            c = Class.forName("com.android.internal.R$dimen");

            obj = c.newInstance();

            field = c.getField("status_bar_height");

            x = Integer.parseInt(field.get(obj).toString());

            sbar = getResources().getDimensionPixelSize(x);

        } catch (Exception e1) {

            e1.printStackTrace();

        }

        return sbar;
    }

    @Override
    protected void initFragment() {

    }

    @Override
    protected void beforePermission() {

    }

    @Override
    protected int setSystemBarColorId() {
        return 0;
    }

    @Override
    public void onClick(View v) {
        Intent intent = null;
        switch (v.getId()) {
            //左上角
            case R.id.iv_left:
                //头像
            case R.id.ci_header:
                intent = new Intent(mContext, UserInfoActivity.class);
                break;
            //蓝牙开门
            case R.id.btn_blue_t:
                if (isBluetoothEnable) {
                    PermissionUtils.askPermission(this, LOCATION_PERMISSION_ASK, permissionCallback, Manifest.permission.ACCESS_COARSE_LOCATION);
                } else {
                    showToast("蓝牙不可用！");
                }
                break;
            //远程开门
            case R.id.btn_net:
                presenter.getDevices();
                break;
            //社区服务
            case R.id.btn_service:
                showToast("功能待开放！");
                break;
            //设备报障
            case R.id.btn_warning:
                startActivity(new Intent(mContext, WarningActivity.class));
//                showToast("功能待开放！");
                break;
            case R.id.iv_right:
                intent = new Intent(mContext, AccreditListActivity.class);
                intent.putExtra(AccreditListActivity.KEY_CACHE_DATAS, (Serializable) pushRequestDatas);
                startActivityForResult(intent, REQ_ACCREDITE_LIST);
                return;
        }
        if (intent != null) {
            startActivity(intent);
        }
    }

    private void checkBlueTooth() {
        boolean isEnableBluetooth = BluetoothOpenDoorUtil.checkBlueTooth(this);
        if (isEnableBluetooth) {
            bluetoothOpenDoor();
        } else {
            Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(intent, REQUEST_ENABLE_BT);
        }
    }

    private void bluetoothOpenDoor() {
        final List<DeviceInfoBean> list = AppConfig.getDeviceList();
        final String[] nameArray = new String[list.size()];
        for (int i = 0; i < list.size(); i++) {
            nameArray[i] = TextUtils.isEmpty(list.get(i).house_name) ? "" : list.get(i).house_name;
        }
        AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
        builder.setTitle("选择门禁");
        builder.setItems(nameArray, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                String name = nameArray[which];
                final DeviceInfoBean deviceBean = list.get(which);
                showConfirmDialog("提示", "确定解锁‘" + name + "’吗？", "确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
//                        showUnCancelLoadingDialog("正在蓝牙开锁...");
                        bluetoothDoOpenDoor(deviceBean.device_name, deviceBean.sn, deviceBean.psd);
                    }
                }, "取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });
            }
        });
        builder.show();

    }

    private void bluetoothDoOpenDoor(String device_name, String sn, String psd) {
        BluetoothOpenDoorUtil.unlockDoor(mContext, device_name, sn, psd, new BluetoothOpenDoorUtil.openDoorCallback() {
            @Override
            public void onSuccess() {
                showToast("开门成功");
            }

            @Override
            public void onFailed(String msg) {
                showToast(msg);
            }
        });
    }

    /**
     * 初始化用户信息
     */
    private void initDatas() {
        UserInfo userInfo = (UserInfo) getIntent().getSerializableExtra(KEY_USERINFO);
        if (userInfo != null) {
            updateUserInfo(userInfo);
        }
        userInfoPresenter.getUserInfo();
    }

    /**
     * 根据用户信息更新界面
     *
     * @param userInfo
     */
    private void updateUserInfo(UserInfo userInfo) {
        if (userInfo == null) {
            return;
        }
        String nick_name = userInfo.getNick_name();
        String sex = userInfo.getSex();
        if (!StringUtils.isEmpty(nick_name)) {
            tv_userName.setText(nick_name);
        }
        Drawable icon_sex = null;
        int header_default = com.cmccgz.baselibrary.R.drawable.n_photo_default;
        switch (sex == null ? "" : sex) {
            case "男":
                icon_sex = ContextCompat.getDrawable(mContext, R.mipmap.icon_man);
                header_default = R.mipmap.img_touxiang;
                break;
            case "女":
                icon_sex = ContextCompat.getDrawable(mContext, R.mipmap.icon_nv);
                header_default = R.mipmap.img_tx_nv;
                break;
            default:
                break;
        }
        tv_userName.setCompoundDrawablesWithIntrinsicBounds(icon_sex, null, null, null);
        ci_header.setImageResource(header_default);
        mViewHelper.getIv_left().setImageResource(header_default);
        if (!StringUtils.isEmpty(userInfo.getImagePath())) {
            GlideUtils.loadImage(mContext, userInfo.getImagePath(),mViewHelper.getIv_left());
           /* GlideUtils.loadHeadImage(mContext, userInfo.getImagePath(), com.cmccgz.baselibrary.R.drawable.n_photo_default, null, new SimpleTarget<GlideDrawable>() {
                @Override
                public void onResourceReady(final GlideDrawable resource, GlideAnimation<? super GlideDrawable> glideAnimation) {
                    ci_header.setImageDrawable(resource);
                    ci_header.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            mViewHelper.getIv_left().setImageDrawable(resource);
                        }
                    }, 500);
                }
            });*/
        }
    }

    @Override
    public void getUserInfoCache(UserInfo userInfo) {
//        updateUserInfo(userInfo);
    }


    @Override
    public void getUserInfoSuccess(final UserInfo userInfo) {
        updateUserInfo(userInfo);
    }

    @Override
    public void getUserInfoFail(String msg) {

    }

    @Override
    protected void onDestroy() {
        if (mReceiver != null) {
            unregisterReceiver(mReceiver);
        }
        BluetoothOpenDoorUtil.clear();
        super.onDestroy();
    }

    @Override
    public void getdata(List<HostMenuBean> datas, List<DeviceInfoBean> fastDatas, List<WebBean> bannerDatas) {

    }

    @Override
    public void dismissLoadingDialog() {
        super.dismissLoadingDialog();
    }

    @Override
    public void getDevicesCache(List<DeviceInfoBean> data) {

    }

    @Override
    public void getDevicesSuccess(List<DeviceInfoBean> deviceList) {
        final Map<String, String> deviceMap = new HashMap<String, String>();
        final String[] nameArray = new String[deviceList.size()];
        for (int i = 0; i < deviceList.size(); i++) {
            deviceMap.put(TextUtils.isEmpty(deviceList.get(i).house_name) ? "" : deviceList.get(i).house_name, deviceList.get(i).device_id);
            nameArray[i] = TextUtils.isEmpty(deviceList.get(i).house_name) ? "" : deviceList.get(i).house_name;
        }
        AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
        builder.setTitle("选择门禁");
        builder.setItems(nameArray, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                String name = nameArray[which];
                final String deviceId = deviceMap.get(name);
                showConfirmDialog("提示", "确定解锁‘" + name + "’吗？", "确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        showLoadingDialog("正在远程开锁...");
                        presenter.openDoor(AppConfig.getMobile(mContext), deviceId);
                    }
                }, "取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });
            }
        });
        builder.show();
    }

    @Override
    public void openDoorSuccess() {
        ToastUtils.show(mContext, "成功开门");
    }

    @Override
    public void showErrorMsg(String errorMsg) {
        ToastUtils.show(mContext, errorMsg);
    }

    @Override
    public void getReqListSuccess(List<PushRequestBean> datas, boolean isNoAccredited) {
        pushRequestDatas.clear();
        if (datas != null) {
            pushRequestDatas.addAll(datas);
        }
        Log.e("inx", "getReqListSuccess: isNoAccredited=" + isNoAccredited);
        mViewHelper.setPointLeftVisable(isNoAccredited);
    }

    @Override
    public void getReqListError(String msg) {

    }

    @Override
    public void setPresenter(HostContract.Presenter presenter) {
        this.presenter = presenter;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case REQUEST_ENABLE_BT:
                if (resultCode == Activity.RESULT_OK) {
                    bluetoothOpenDoor();
                } else {
                    showToast("请打开蓝牙！");
                }
                break;
            case REQ_ACCREDITE_LIST:
                if (resultCode != Activity.RESULT_OK)
                    return;
                boolean isNoAccredited = data != null && data.getBooleanExtra(AccreditListActivity.KEY_NO_ACCREDITED, false);
                mViewHelper.setPointLeftVisable(isNoAccredited);
                Log.e("inx", "onActivityResult: isNoAccredited=" + isNoAccredited);
                break;
        }
       /* boolean isOpen = (requestCode == REQUEST_ENABLE_BT && resultCode == Activity.RESULT_OK);
        if (isOpen) {
            bluetoothOpenDoor();
        } else {
            showToast("请打开蓝牙！");
        }*/
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == LOCATION_PERMISSION_ASK) {
            PermissionUtils.handlePermissionRequest(permissions, grantResults, this, permissionCallback, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                }
            });
        }
    }

}
